package com.android.waterdetection.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.waterdetection.R;
import com.android.waterdetection.adapter.DeviceDataAdapter;
import com.android.waterdetection.bean.DeviceData;
import com.android.waterdetection.bean.UserBean;
import com.android.waterdetection.dao.DBService;
import com.android.waterdetection.event.GetDeviceDataEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class HomeFragment extends Fragment {

    private static final String TAG = "HomeFragment";

    private RecyclerView mRvData;
    private DeviceDataAdapter mDeviceDataAdapter;
    private List<DeviceData> mDeviceData;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        EventBus.getDefault().register(this);

        initView(root);
        initData();
        initListener();
        return root;
    }

    private void initListener() {

    }

    private void initData() {
        new Thread(() -> {
            mDeviceData = DBService.queryDeviceData();

            if (mDeviceData != null) {
                EventBus.getDefault().post(new GetDeviceDataEvent(true));
            }
        }).start();
    }

    private void initView(View root) {
        mRvData = root.findViewById(R.id.rv_data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getDeviceDataSuccess(GetDeviceDataEvent event) {
        mRvData.setLayoutManager(new LinearLayoutManager(requireContext(),RecyclerView.VERTICAL,false));
        mDeviceDataAdapter = new DeviceDataAdapter(mDeviceData);
        mRvData.addItemDecoration(new DividerItemDecoration(requireContext(),DividerItemDecoration.VERTICAL));
        mRvData.setAdapter(mDeviceDataAdapter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}